package com.example.administrator.yuejian35.Find.activity;

import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.yuejian35.Config;
import com.example.administrator.yuejian35.Find.FindFileUtils;
import com.example.administrator.yuejian35.Find.FindModel;
import com.example.administrator.yuejian35.Find.FindServer;
import com.example.administrator.yuejian35.Find.GlideLoader;
import com.example.administrator.yuejian35.Find.ServiceGenerator;
import com.example.administrator.yuejian35.Home.bean.Result;
import com.example.administrator.yuejian35.MainActivity;
import com.example.administrator.yuejian35.R;
import com.justin.bieber.image.ImageConfig;
import com.justin.bieber.image.ImageSelector;
import com.justin.bieber.image.ImageSelectorActivity;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class AddPostActivity extends AppCompatActivity {

    private ImageButton  btn2;
    private EditText content;
    private ArrayList<String> path = new ArrayList<>();
    private Button back,submit;

    public static final int REQUEST_CODE = 123;

    private ImageConfig imageConfig;

    private LinearLayout llContainer;

    private String Uid;

    private Uri uri;

    List<File> file1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_post);

        btn2 = (ImageButton) findViewById(R.id.img_btn_addpic);
        content = (EditText) findViewById(R.id.post_add_content);
        llContainer = (LinearLayout) findViewById(R.id.llContainer);
        back = (Button) findViewById(R.id.addpost_btn_back);
        submit = (Button) findViewById(R.id.addpost_btn_submit);

        MainActivity mainActivity = new MainActivity();
        Uid = mainActivity.getUserId();

        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                imageConfig = new ImageConfig.Builder(
                        new GlideLoader())
                        .steepToolBarColor(getResources().getColor(R.color.titleBlue))
                        .titleBgColor(getResources().getColor(R.color.titleBlue))
                        .titleSubmitTextColor(getResources().getColor(R.color.white))
                        .titleTextColor(getResources().getColor(R.color.white))
                        // 开启多选   （默认为多选）
                        .mutiSelect()
                        // 多选时的最大数量   （默认 9 张）
                        .mutiSelectMaxSize(9)
                        //设置图片显示容器，参数：、（容器，每行显示数量，是否可删除）
                        .setContainer(llContainer, 4, true)
                        // 已选择的图片路径
                        .pathList(path)
                        // 拍照后存放的图片路径（默认 /temp/picture）
                        .filePath("/temp")
                        // 开启拍照功能 （默认关闭）
                        .showCamera()
                        .requestCode(REQUEST_CODE)
                        .build();
                ImageSelector.open(AddPostActivity.this, imageConfig);
            }
        });

        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addmore();

            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK && data != null) {
            List<String> pathList = data.getStringArrayListExtra(ImageSelectorActivity.EXTRA_RESULT);

            path.clear();
            path.addAll(pathList);
        }
    }


    private void addmore() {
        Map<String, RequestBody> params = new HashMap<>();

        for(int i=0;i<path.size();i++){
            File file = new File(path.get(i));
            RequestBody  requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
            //一定要加("AttachmentKey\"; filename=\"" +，不然失败
            params.put("file[]\"; filename=\"" +file.getName(),requestFile);
        }



        FindModel findModel = new FindModel();

        String context = String.valueOf(content.getText());

        Call<Result> call = findModel.addmore(Uid,context,params);
        call.enqueue(new Callback<Result>() {
            @Override
            public void onResponse(Call<Result> call,Response<Result> response) {
                Toast.makeText(AddPostActivity.this,"发布成功！！！",Toast.LENGTH_SHORT).show();
                finish();
            }

            @Override
            public void onFailure(Call<Result> call, Throwable t) {
                Log.e("Upload error:", t.getMessage());
            }
        });

    }


    private void addPost() {

        File file = new File(path.get(0));

        RequestBody requestFile =
                RequestBody.create(MediaType.parse("multipart/form-data"), file);


        MultipartBody.Part body =
                MultipartBody.Part.createFormData("file[]", file.getName(), requestFile);

        FindModel findModel = new FindModel();

        String context = String.valueOf(content.getText());

        Call<Result> call = findModel.addpost(1,context,body);
        call.enqueue(new Callback<Result>() {
            @Override
            public void onResponse(Call<Result> call,Response<Result> response) {
                Toast.makeText(AddPostActivity.this,"发布成功！！！",Toast.LENGTH_SHORT).show();
                finish();
            }

            @Override
            public void onFailure(Call<Result> call, Throwable t) {
                Log.e("Upload error:", t.getMessage());
            }
        });

    }

}
